<?php

namespace app\services;

use app\payment\PayFactory;
use app\traits\Page;
use plugin\admin\app\model\UserPropertyLog;
use plugin\admin\app\model\UserSignLog;

class UserSignService
{
    public static function getSignDates($userId)
    {
        $startDate = date('Y-m-01');
        $endDate = date('Y-m-t');
        $limit = substr($endDate, 8);

        for ($i=0; $i<$limit; $i++) {
            $date = date('Y-m-d', strtotime($startDate . ' + ' . $i . ' days'));
            $isSigned = self::isSigned($userId, $date);
            $dates[] = [
                'date' => $date,
                'is_sign' => $isSigned
            ];
        }

        return $dates;
    }

    public static function signInfo($userId)
    {
        $startTime = date('Y-m-01 00:00:00');
        $endTime = date('Y-m-t 23:59:59');

        $signDays = UserSignLog::where('user_id', $userId)->whereBetween('sign_date', [$startTime, $endTime])->count();
        return [
            'sign_days' => $signDays,
            'integral' => ConfigService::get('sign_integral'),
            'today_is_sign' => self::isSigned($userId, date('Y-m-d H:i:s'))
        ];
    }

    public static function getList($userId, $page = 1, $length = 10)
    {
        $offset = ($page - 1) * $length;

        $query = UserSignLog::where('user_id', $userId);

        $totalCount = (clone $query)->count();
        $list = (clone $query)->offset($offset)->limit($length)->orderByDesc('sign_date')->get()->toArray();

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function sign($userId)
    {
        $date = date('Y-m-d H:i:s');
        $integral = ConfigService::get('sign_integral');
        if (self::isSigned($userId, $date)) {
            throw new \Exception('当天已签到');
        }

        UserSignLog::insert([
            'user_id' => $userId,
            'sign_date' => $date,
            'integral' => $integral
        ]);

        PropertyService::add($userId, PayFactory::INTEGRAL, $integral, UserPropertyLog::INTEGRAL_INCOME_SIGN);
    }

    public static function isSigned($userId, $date)
    {
        $startDate = date('Y-m-d 00:00:00', strtotime($date));
        $endDate = date('Y-m-d 23:59:59', strtotime($date));
        return UserSignLog::where('user_id', $userId)->whereBetween('sign_date', [$startDate, $endDate])->count() > 0;
    }
}